/*
 * Copyright (C) 2015-2016  Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */


#include "PlanetWars2dRT-core/specific/controller/planet_collision.h"
#include "PlanetWars2dRT-core/specific/model/planet_life.h"
#include "PlanetWars2dRT-core/specific/model/planet_state.h"
#include "PlanetWars2dRT-core/specific/model/planet_player.h"
#include "PlanetWars2dRT-core/specific/model/ship_life.h"
#include "PlanetWars2dRT-core/specific/model/ship_move.h"
#include "PlanetWars2dRT-core/specific/model/players_info.h"


EXTERN_C_BEGIN


void
planet_collision_with_other_player_not_destroyed_ship(planet_t*     a_planet,
						      const ship_t* a_ship)
{
  planet_reduce_life(a_planet, a_ship->power);

  if(a_planet->life_current == 0)
    {
      if(planet_is_neutral(a_planet))
	{
	  planet_set_player_index_unsafe(a_planet, a_ship->player_index);
	}
      else
	{
	  planet_set_player_index_unsafe(a_planet, NULL_PLAYER_INDEX);
	}
      a_planet->life_current = a_planet->life_max;
    }
}

bool
planet_collision_with_other_player_ship(planet_t*     a_planet,
					const ship_t* a_ship)
{
  if(ship_is_destroyed(a_ship))
    {
      return false;
    }
  planet_collision_with_other_player_not_destroyed_ship(a_planet, a_ship);
  return true;
}

bool
planet_collision_with_not_destroyed_ship(planet_t*     a_planet,
					 const ship_t* a_ship)
{
  if(a_ship->player_index != a_planet->player_index)
    {
      planet_collision_with_other_player_not_destroyed_ship(a_planet, a_ship);
      return true;
    }
  
  if(!ship_is_moving(a_ship) &&
     planet_get_life_current_unsafe(a_planet) + ship_get_life_current_unsafe(a_ship)
     <= planet_get_life_max_unsafe(a_planet))
    {
      a_planet->life_current += ship_get_life_current_unsafe(a_ship);
      return true;
    }
  
  return false;
}

bool
planet_collision_with_ship(planet_t*     a_planet,
			   const ship_t* a_ship)
{
  return
    ship_is_destroyed(a_ship)
    ? false
    : planet_collision_with_not_destroyed_ship(a_planet, a_ship);
}


EXTERN_C_END
